using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Helpers;
using AvalonAdmin.Models;
using AvalonAdmin.Pages.CarType.ViewModels.Brand;
using AvalonAdmin.Pages.CarType.Views.Brand;
using AvalonAdminDto.Common;

using AvalonAdminDto.Rule.RuleConfigDtos;
using D.UtilCore.Dtos;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Ursa.Controls;

namespace AvalonAdmin.Pages.Rule.ViewModels.RuleConfig
{
    /// <summary>
    /// 规则配置修改视图模型
    /// </summary>
    public class RuleConfigModifyViewModel : BaseModifyViewModel
    {
        #region 属性字段
        private string? _id;
        private string? _brand;
        private string? _name;
        private string? _no;
        private string? _description;
        private int? _brandId;
        private ObservableCollection<RuleConfigDetails> _ruleConfigDetailsList = new ObservableCollection<RuleConfigDetails>();
        #endregion

        #region 属性
        /// <summary>
        /// 规则配置ID
        /// </summary>
        public string? Id
        {
            get => _id;
            set => SetProperty(ref _id, value);
        }

        /// <summary>
        /// 品牌名称
        /// </summary>
        [Required(ErrorMessage = "品牌不能为空")]
        public string? Brand
        {
            get => _brand;
            set => SetProperty(ref _brand, value);
        }

        /// <summary>
        /// 规则名称
        /// </summary>
        [Required(ErrorMessage = "规则名称不能为空")]
        public string? Name
        {
            get => _name;
            set => SetProperty(ref _name, value);
        }

        /// <summary>
        /// 规则编号
        /// </summary>
        [Required(ErrorMessage = "规则编号不能为空")]
        public string? No
        {
            get => _no;
            set => SetProperty(ref _no, value);
        }

        /// <summary>
        /// 规则描述
        /// </summary>
        public string? Description
        {
            get => _description;
            set => SetProperty(ref _description, value);
        }

        /// <summary>
        /// 品牌ID
        /// </summary>
        public int? BrandId
        {
            get => _brandId;
            set => SetProperty(ref _brandId, value);
        }

        /// <summary>
        /// 规则配置详情列表
        /// </summary>
        public ObservableCollection<RuleConfigDetails> RuleConfigDetailsList
        {
            get => _ruleConfigDetailsList;
            set => SetProperty(ref _ruleConfigDetailsList, value);
        }

        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public RuleConfigModifyViewModel()
        {
            LoadData();
        }
        #endregion

        #region 方法
        /// <summary>
        /// 加载数据
        /// </summary>
        public async void LoadData()
        {
            if (!string.IsNullOrEmpty(Id))
            {
                await ExecuteWithLoadingAsync(async () =>
                {
                    var res = await HttpHelper<RepRuleConfig>.GetAsync($"{ApiUrl.GetRuleConfig}/{Id}");
                    if (res.Code == StatusCodeEnum.OK && res.Data != null)
                    {
                        Name = res.Data.Name;
                        No = res.Data.No;
                        Description = res.Data.Descption;
                        BrandId = res.Data.BrandId;
                        
                        // 获取品牌信息
                        var brandRes = await HttpHelper<RepBrand>.GetAsync($"{ApiUrl.GetBrand}/{res.Data.BrandId}");
                        if (brandRes.Code == StatusCodeEnum.OK && brandRes.Data != null)
                        {
                            Brand = brandRes.Data.Name;
                        }
                        
                        // 加载规则配置详情
                        if (res.Data.RuleConfigDetailsList != null)
                        {
                            RuleConfigDetailsList.Clear();
                            foreach (var item in res.Data.RuleConfigDetailsList)
                            {
                                RuleConfigDetailsList.Add(item);
                            }
                        }
                    }
                    else
                    {
                        ShowWarning($"加载数据失败: {res.Msg}");
                    }
                });
            }
        }
        #endregion

        #region 数据提交方法

        /// <summary>
        /// 提交数据
        /// </summary>
        /// <returns></returns>
        protected override async Task<bool> SubmitAsync()
        {
            // 验证必填字段
            if (string.IsNullOrEmpty(Name))
            {
                ShowWarning("规则名称不能为空");
                return false;
            }
            if (string.IsNullOrEmpty(No))
            {
                ShowWarning("规则编号不能为空");
                return false;
            }
            if (BrandId == null)
            {
                ShowWarning("品牌不能为空");
                return false;
            }

            var ruleConfig = new RepRuleConfig
            {
                Name = Name,
                No = No,
                Descption = Description,
                BrandId = BrandId.Value,
                RuleConfigDetailsList = RuleConfigDetailsList.ToList()
            };

            try
            {
                ApiResponse<RepRuleConfig> response;
                if (!string.IsNullOrEmpty(Id))
                {
                    // 更新
                    ruleConfig.Id = Id;
                    response = await HttpHelper<RepRuleConfig>.PutAsync(ApiUrl.UpdateRuleConfig, ruleConfig);
                }
                else
                {
                    // 新增
                    response = await HttpHelper<RepRuleConfig>.PostAsync(ApiUrl.AddRuleConfig, ruleConfig);
                }

                return HandleApiResponse(response, string.IsNullOrEmpty(Id) ? "添加成功" : "修改成功");
            }
            catch (Exception ex)
            {
                ShowWarning($"操作失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void ResetForm()
        {
            Id = null;
            Name = null;
            No = null;
            Description = null;
            Brand = null;
            BrandId = null;
            RuleConfigDetailsList.Clear();
        }

        /// <summary>
        /// 选择品牌
        /// </summary>
        public async void SelectBrand()
        {
            var res = await Dialog.ShowModal<Page_Brand_Query, BrandQueryViewModel>(new BrandQueryViewModel(), null, options: GetDialogOptions("品牌查询"));
            if (res == DialogResult.OK)
            {
                // 刷新数据
                LoadData();
            }
        }

        /// <summary>
        /// 添加详情
        /// </summary>
        public async void AddDetails()
        {
            var res = await Dialog.ShowModal<Page_RuleConfigDetails_Modify, RuleConfigDetailsModifyViewModel>(new RuleConfigDetailsModifyViewModel(), null, options: GetDialogOptions("添加详情"));
            if (res == DialogResult.OK)
            {
                LoadData();
            }
        }

        /// <summary>
        /// 批量删除详情
        /// </summary>
        public void BatchDeleteDetails(object? obj)
        {
            if (obj is ObservableCollection<RuleConfigDetails> selectedItems)
            {
                var itemsToRemove = selectedItems.Where(a => a.IsSelected == true).ToList();
                foreach (var item in itemsToRemove)
                {
                    RuleConfigDetailsList.Remove(item);
                }
            }
        }

        #endregion

        #region 抽象方法实现
        public async Task AddAsync(RepRuleConfig? item = null)
        {
            // 新增功能通过Submit方法实现
            await Task.CompletedTask;
        }

        public async Task UpdateAsync(RepRuleConfig? item = null)
        {
            // 修改功能通过Submit方法实现
            await Task.CompletedTask;
        }

        public async Task DeleteAsync(RepRuleConfig? item = null)
        {
            if (item != null && !string.IsNullOrEmpty(item.Id))
            {
                try
                {
                    var res = await HttpHelper<RepRuleConfig>.DeleteAsync($"{ApiUrl.DeleteRuleConfig}/{item.Id}");
                    if (res.Code == StatusCodeEnum.OK)
                    {
                        await MessageBox.ShowAsync("删除成功");
                    }
                    else
                    {
                        await MessageBox.ShowAsync(res.Msg);
                    }
                }
                catch (Exception ex)
                {
                    await MessageBox.ShowAsync("删除异常: " + ex.Message);
                }
            }
        }

        public async Task BatchDeleteAsync(IEnumerable<RepRuleConfig>? items = null)
        {
            if (items != null && items.Any())
            {
                try
                {
                    var ids = items.Select(x => x.Id).ToList();
                    var res = await HttpHelper<List<string>>.PostAsync(ApiUrl.BatchDeleteRuleConfig, ids);
                    if (res.Code == StatusCodeEnum.OK)
                    {
                        await MessageBox.ShowAsync("批量删除成功");
                    }
                    else
                    {
                        await MessageBox.ShowAsync(res.Msg);
                    }
                }
                catch (Exception ex)
                {
                    await MessageBox.ShowAsync("批量删除异常: " + ex.Message);
                }
            }
        }

        protected bool GetIsSelected(RepRuleConfig item)
        {
            return item.IsSelected;
        }

        protected void SetIsSelected(RepRuleConfig item, bool isSelected)
        {
            item.IsSelected = isSelected;
        }

        public async Task<IEnumerable<RepRuleConfig>> QueryAsync()
        {
            // 查询功能待实现
            await Task.CompletedTask;
            return new List<RepRuleConfig>();
        }
        #endregion
    }
}



